package beer.xz.beer.device.data.api

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory


object Apis {
    private val loggingInterceptor = HttpLoggingInterceptor().apply {
        level = ApiConfig.logLevel
    }
    private val clientWithoutSecretKey =
        OkHttpClient.Builder().addInterceptor(loggingInterceptor).build()
    private val clientWithSecretKey = OkHttpClient.Builder().addInterceptor(loggingInterceptor)
        .addInterceptor(SecretKeyInterceptor()).build()

    private val retrofitWithoutSecretKey =
        Retrofit.Builder().baseUrl(ApiConfig.baseUrl) // 替换为你的后端 API 基础 URL
            .client(clientWithoutSecretKey).addConverterFactory(GsonConverterFactory.create())
            .build()

    private val retrofit = Retrofit.Builder().baseUrl(ApiConfig.baseUrl) // 替换为你的后端 API 基础 URL
        .client(clientWithSecretKey).addConverterFactory(GsonConverterFactory.create()).build()


    val ControllerSecretKeyService: ControllerSecretKeyApi =
        retrofitWithoutSecretKey.create(ControllerSecretKeyApi::class.java)

    //DeviceStatus Api
    val DeviceStatusService: DeviceStatusApi = retrofit.create(DeviceStatusApi::class.java)

    //Device Api
//    val DeviceService: DeviceApi = retrofit.create(DeviceApi::class.java)
    // Channel Api
    val ChannelService: ChannelApi = retrofit.create(ChannelApi::class.java)

    // Product Api
    val ProductService: ProductApi = retrofit.create(ProductApi::class.java)
}


class SecretKeyInterceptor() : okhttp3.Interceptor {
    override fun intercept(chain: okhttp3.Interceptor.Chain): okhttp3.Response {
        if (!ApiConfig.isSecretKeyValid()) throw Exception("SecretKey is not valid")
        val request = chain.request()
        val newRequest =
            request.newBuilder().addHeader("Authorization", "Bearer ${ApiConfig.getSecretKey()!!}")
                .build()
        return chain.proceed(newRequest)
    }
}